package org.unique.sys;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unique.Const;
import org.unique.commons.io.IOUtil;
import org.unique.ioc.annotation.Component;
import org.unique.support.orm.ds.DataSourceFactory;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * druid数据源
 * @author biezhi
 * @version 1.0
 */
@Component
public class DruidDataSource implements DataSourceFactory{

	private Logger logger = LoggerFactory.getLogger(DruidDataSource.class);
	
	private DataSource dataSource;
	
	/**
	 * 获取数据源
	 */
	public DataSource getDataSource() {
		if(null == dataSource){
			if(Const.getConfig("unique.db.pooltype").equalsIgnoreCase("druid")){
				String dbfile = Const.getConfig("unique.db.config");
				InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(dbfile);
		        if(null != in){
		        	try {
		        		Properties properties = new Properties();// 读取配置文件
		                properties.load(in);
		                IOUtil.closeQuietly(in);
		                dataSource = DruidDataSourceFactory.createDataSource(properties);
		            } catch (IOException e) {
		                logger.error(e.getMessage());
		            } catch (Exception e) {
		                logger.error(e.getMessage());
		            }
		        }
			}
		}
		return dataSource;
	}

}
